import {
  Card,
  Table,
  TableProps,
  Tag,
  Popconfirm,
  Button,
  message,
  Pagination,
} from 'antd';
import SearchUser from './SearchUser';
import { UserData, UserSearch } from '@/types/sys';
import Dialog from './Dialog';
import { useCallback, useState, useEffect } from 'react';
import { getUserList, deleteUser } from '@/api/sys';
import { pageation as paginationInterface } from '@/types/global';
import LazyImage from '@/components/LazyImage.tsx';

const ActionButtons = ({
  onEdit,
  onDelete,
}: {
  onEdit: () => void;
  onDelete: () => void;
}) => (
  <>
    <Button type="primary" onClick={onEdit}>
      编辑
    </Button>
    <Popconfirm
      title="确定要删除此用户吗？"
      onConfirm={onDelete}
      okText="是"
      cancelText="否"
    >
      <Button type="primary" danger>
        删除
      </Button>
    </Popconfirm>
  </>
);

function User() {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState<UserSearch>({});
  const [record, setRecord] = useState<UserData | null>(null);
  const [data, setData] = useState<UserData[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [pagination, setPagination] = useState<paginationInterface>({
    page: 1,
    pageSize: 10,
  });

  const columns: TableProps<UserData>['columns'] = [
    {
      title: 'ID',
      align: 'center',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '账号',
      align: 'center',
      dataIndex: 'accessor',
      key: 'accessor',
    },
    {
      title: '昵称',
      align: 'center',
      dataIndex: 'nickname',
      key: 'nickname',
    },
    {
      title: '头像',
      align: 'center',
      dataIndex: 'avatar',
      key: 'avatar',
      render: (_: unknown, record: UserData) => {
        return record.accessor ? (
          <LazyImage src={record.avatar || ''} alt="avatar" />
        ) : (
          '无'
        );
      },
    },
    {
      title: '邮箱',
      align: 'center',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '手机号',
      align: 'center',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'status',
      key: 'status',
      render: (_: unknown, record: UserData) => {
        return !(record.status !== 1) ? (
          <Tag color="success">启用</Tag>
        ) : (
          <Tag color="error">禁用</Tag>
        );
      },
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'create_time',
      key: 'create_time',
    },
    {
      title: '更新时间',
      align: 'center',
      dataIndex: 'update_time',
      key: 'update_time',
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'operation',
      key: 'operation',
      render: (_: unknown, record: UserData) => (
        <ActionButtons
          onEdit={() => handleEdit(record)}
          onDelete={() => handleDelete(record)}
        />
      ),
    },
  ];

  // 动态计算表格高度
  const fetchData = async (
    params: UserSearch,
    pagination?: { page: number; pageSize: number }
  ) => {
    const data = {
      page: pagination?.page || 1,
      pageSize: pagination?.pageSize || 10,
      ...params,
    };
    const result = await getUserList(data);
    console.log('result-------user', result);
    if (!result) return;
    const { list, total }: unknown = result.data;
    console.log('list', list);
    console.log('total', total);
    setData(list);
    setTotal(total);
  };

  const handleSearch = useCallback((values: UserSearch) => {
    setPagination({
      page: 1,
      pageSize: 5,
    });
    setQuery(values);
  }, []);

  const handleAdd = useCallback(() => {
    setRecord(null);
    setOpen(true);
  }, []);

  const handleEdit = (record: UserData) => {
    setRecord(record);
    setOpen(true);
  };

  const handleDelete = async (record: UserData) => {
    try {
      await deleteUser(record.id as string);
      message.success('删除成功');
      fetchData(query, pagination);
    } catch {
      message.error('删除失败');
    }
  };

  const handleTableChange = (page: number, pageSize: number) => {
    setPagination({
      page: page,
      pageSize: pageSize,
    });
  };
  useEffect(() => {
    fetchData(query, pagination);
  }, [query, pagination]);
  return (
    <>
      <div className="flex-page-layout">
        <Card className=" w-full">
          <SearchUser onFinish={handleSearch} onAdd={handleAdd}></SearchUser>
        </Card>

        <Table
          virtual
          scroll={{ x: 1200, y: 'auto' }}
          bordered={true}
          showSorterTooltip
          columns={columns}
          rowKey="id"
          dataSource={data}
          pagination={false}
        ></Table>

        <div>
          <Pagination
            pageSize={pagination.pageSize}
            total={total}
            current={pagination.page}
            pageSizeOptions={[10, 20, 50, 100]}
            showTotal={(total) => `共 ${total} 条`}
            onChange={(page, pageSize) => handleTableChange(page, pageSize)}
            showSizeChanger
            showQuickJumper
          />
        </div>
      </div>
      <Dialog
        open={open}
        title={record ? '编辑用户' : '添加用户'}
        setOpen={setOpen}
        record={record}
        onSave={() => {
          handleSearch(query);
        }}
      />
    </>
  );
}

export default User;
